package com.adam.example.aggregation.bucket;

import com.adam.example.TransportClientHolder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.range.geodistance.GeoDistanceAggregationBuilder;

import java.net.UnknownHostException;

public class GeoDistanceAggregationExample {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient transportClient = TransportClientHolder.getInstance().getTransportClient();

        GeoDistanceAggregationBuilder geoDistanceAggregationBuilder = AggregationBuilders.geoDistance("agg",
                new GeoPoint(34.3412700000, 108.9398400000)).field("location").unit(DistanceUnit.KILOMETERS)
                .addUnboundedTo(500).addRange(500, 1000).addUnboundedFrom(1000);
        SearchResponse searchResponse = transportClient.prepareSearch("test")
                        .setSize(0).addAggregation(geoDistanceAggregationBuilder).get();
        Range range = searchResponse.getAggregations().get("agg");
        for(Range.Bucket bucket: range.getBuckets()) {
            System.out.println(bucket.getKey() + "(" + bucket.getFrom() + "-" + bucket.getTo() + "):" + bucket.getDocCount());
            //getFrom/getTo返回的是Double类型，可能是0或正无穷大，通过Double.isInfinity判断无穷大，通过Double.equals(Double.POSITIVE_INFINITY)比较正无穷大
        }

        transportClient.close();
    }

}
